package com.ruoyi.system.utils.rabbitMq.direct;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.webservice.SoapClient;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.ruoyi.system.constant.IpAddressConstant;
import com.ruoyi.system.domain.HUAWEI.*;
import com.ruoyi.system.domain.InterfaceLog;
import com.ruoyi.system.domain.MES.*;
import com.ruoyi.system.domain.MqExceptionData;
import com.ruoyi.system.domain.WMS.RptInPackageDTO;
import com.ruoyi.system.domain.function.ProdOrder;
import com.ruoyi.system.domain.function.ProdPlan;
import com.ruoyi.system.enums.MaterialEnum;
import com.ruoyi.system.enums.MesEnum;
import com.ruoyi.system.enums.RabbitMqEnum;
import com.ruoyi.system.mapper.HUAWEI.*;
import com.ruoyi.system.mapper.InterfaceLogMapper;
import com.ruoyi.system.mapper.MES.*;
import com.ruoyi.system.mapper.MqExceptionDataMapper;
import com.ruoyi.system.mapper.ProdOrderMapper;
import com.ruoyi.system.mapper.ProdPlanMapper;
import com.ruoyi.system.service.IBaseSerialNumberService;
import com.ruoyi.system.service.WMSService;
import com.ruoyi.system.utils.InterfaceLogUtil.InterfaceLogUtil;
import com.ruoyi.system.utils.huaweiInterfaceUtil.HuaweiInterfaceHttps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author
 * @title: DirectReceiver
 * @projectName zhengxiong.jiang
 * @description: TODO
 * @date 2019-6-24 10:25
 */
@Component
public class DirectReceiver {

    private final static Logger logger = LoggerFactory.getLogger(DirectReceiver.class);

    @Autowired
    private InterfaceLogMapper interfaceLogMapper;
    @Autowired
    private IBaseSerialNumberService iBaseSerialNumberService;
    @Autowired
    private ProdOrderMapper prodOrderMapper;
    @Autowired
    private ProdPlanMapper prodPlanMapper;
    @Autowired
    private KeymatBindMapper keymatBindMapper;
    @Autowired
    private MaterialDatasMapper datasMapper;
    @Autowired
    private DataCollectionMapper dataCollectionMapper;
    @Autowired
    private DataCollectionInfoMapper dataCollectionInfoMapper;
    @Autowired
    private MesAralmMapper mesAralmMapper;
    @Autowired
    private EmsBarcodeMaterialMapper emsBarcodeMaterialMapper;
    @Autowired
    private TBtpMtlCurriculumViateTiMapper tbmapper;
    @Autowired
    private EmsBarcodeRelationMapper emsBarcodeRelationMapper;
    @Autowired
    private EmsBarcodeAttributeMapper emsBarcodeAttributeMapper;
    @Autowired
    private EmsCustomerSnMapper emsCustomerSnMapper;
    @Autowired
    private WMSService wmsService;
    @Autowired
    private EmsBarcodeShipmentMapper shipmentMapper;

    @Autowired
    private InterfaceLogUtil interfaceLogUtil;
    @Autowired
    private MqExceptionDataMapper mqExceptionDataMapper;


    @RabbitListener(queues = "MES_TO_MOM_KEYMAT_BIND")
    public void keymatBind(byte[] data, Channel channel, Message message) throws IOException {

        //开始消费的时间
        Date startDate = new Date();

        try {
            Map maps = (Map) JSON.parse(new String(data, CharsetUtil.UTF_8));
            Object body = maps.get("Body");
            String jsonDatas = JSONUtil.toJsonStr(body);
            logger.info("MES_TO_MOM_KEYMAT_BIND收到:{},收到时间:{}", jsonDatas, DateUtil.now());
            //你的业务逻辑
            KeymatBindDTO keymatBindDTO = JSONUtil.toBean(jsonDatas, KeymatBindDTO.class);
            KeymatBind keymatBind = new KeymatBind();
            BeanUtils.copyProperties(keymatBindDTO, keymatBind);
            keymatBind.setCreateBy("admin");
            keymatBind.setCreateTime(new Date());
            keymatBindMapper.insert(keymatBind);
            List<MaterialDatasDTO> materialList = keymatBindDTO.getMaterialList();
            if (IterUtil.isNotEmpty(materialList)) {
                materialList.stream().forEach(i -> {
                    MaterialDatas materialDatas = new MaterialDatas();
                    BeanUtils.copyProperties(i, materialDatas);
                    materialDatas.setBindId(keymatBind.getBindId());
                    materialDatas.setCreateBy("admin");
                    materialDatas.setCreateTime(new Date());
                    datasMapper.insert(materialDatas);
                    //根据物料编码筛选华为物料，进行区分sn，09、psn 逻辑取消
//                            MaterialDataErp materialDataErp = materialDataErpMapper.selectByCode(i.getFMaterielCode());
                    if (i.getFMaterialType().equals(MaterialEnum.B_INW_BATCH_PSN.getDesc())) {//psn/09
                        logger.info("=====================psn消费开始====================");
                        EmsBarcodeMaterial barcodeMaterial = new EmsBarcodeMaterial();
                        ProdOrder prodOrder = prodOrderMapper.selectOne(new QueryWrapper<ProdOrder>().eq("order_code", keymatBindDTO.getFPlanNo()));
                        String taskTon = prodOrder.getTaskTon();

                        barcodeMaterial.setPo(taskTon);
                        barcodeMaterial.setBarCode(keymatBindDTO.getFNumber());
                        barcodeMaterial.setItemCode(i.getFMaterielCode());
                        List<TBtpMtlCurriculumViateTi> list = tbmapper.selectList(new QueryWrapper<TBtpMtlCurriculumViateTi>()
                                .eq("item_code", i.getFMaterielCode())
                                .eq("barcode", i.getFMaterielBarcode())
                                .eq("process_name", "任务令发料")
                                .eq("task_no", taskTon)
                                .orderByDesc("created_date")
                        );

                        if (IterUtil.isNotEmpty(list)) {
                            barcodeMaterial.setDateCode(list.get(0).getDateCode());
                            barcodeMaterial.setLotCode(list.get(0).getLotCode());
                        }

                        //通过工单找到对应物料清单的数量
                        ProdPlan prodPlan = prodPlanMapper.selectOne(new QueryWrapper<ProdPlan>().eq("plan_code", prodOrder.getPlanCode()));
//                                    BomInfoErp bomInfoErp = bomInfoErpMapper.selectOne(new QueryWrapper<BomInfoErp>().eq("order_id", prodPlan.getScddErpId())
//                                            .eq("child_code", i.getFMaterielCode()));
//                                    if(ObjectUtil.isNotNull(bomInfoErp)){
//                                        barcodeMaterial.setQuantity(bomInfoErp.getBaseQuantity());
//                                    }
                        barcodeMaterial.setQuantity(Double.valueOf(i.getPatchCount()));
                        barcodeMaterial.setVendorId("22827731");//华为默认
                        barcodeMaterial.setOrgId(157);//华为默认
                        barcodeMaterial.setCreatedDate(i.getFDate());
                        barcodeMaterial.setCreatedBy("马鞍山工厂");
                        barcodeMaterial.setUploadFlag(0);
                        String fMaterielBarcode = i.getFMaterielBarcode();

                        //todo 临时逻辑 后续可能会删除此逻辑
                        if (StrUtil.isNotEmpty(fMaterielBarcode) && fMaterielBarcode.contains("#")) {
                            String[] split = fMaterielBarcode.split("#");
                            if (split.length > 0) {
                                fMaterielBarcode = split[0];//split[1]date_code split[2]lot_code
                            }
                            if (split.length > 1) {
                                barcodeMaterial.setDateCode(split[1]);
                            }
                            if (split.length > 2) {
                                barcodeMaterial.setLotCode(split[2]);
                            }
                        }
                        List<TBtpMtlCurriculumViateTi> list2 = tbmapper.selectList(new QueryWrapper<TBtpMtlCurriculumViateTi>()
                                .eq("barcode", i.getFMaterielBarcode())
                                .orderByDesc("created_date")
                        );
                        if (IterUtil.isNotEmpty(list2)) {
                            barcodeMaterial.setSupplier(list2.get(0).getMtlVendorName());
                        }

                        barcodeMaterial.setSegment1(fMaterielBarcode);
                        barcodeMaterial.setSegment2("N");
                        barcodeMaterial.setSegment4(prodPlan.getTaskTon());
                        barcodeMaterial.setSegment13(i.getFMaterielBarcode());
                        barcodeMaterial.setSegment14("40033");
                        barcodeMaterial.setSegment15("EMS");
                        barcodeMaterial.setPtionSegment(i.getFMaterielCode().substring(0, 2) + "22827731");
                        barcodeMaterial.setBarItemCode(keymatBind.getFProdCodeNo());
                        barcodeMaterial.setEmsTransId(iBaseSerialNumberService.getSerialNumber("H4", 16));
                        emsBarcodeMaterialMapper.insert(barcodeMaterial);
                        logger.info("=====================psn消费结束====================");
                    } else if (i.getFMaterialType().equals(MaterialEnum.B_INW_BATCH_SN.getDesc())) {
                        logger.info("=====================sn消费开始====================");
                        String h4 = iBaseSerialNumberService.getSerialNumber("H4", 8);
                        ProdOrder prodOrder = prodOrderMapper.selectOne(new QueryWrapper<ProdOrder>().eq("order_code", keymatBindDTO.getFPlanNo()));
                        String taskTon = prodOrder.getTaskTon();
                        String mtlVendorName = "";
                        List<TBtpMtlCurriculumViateTi> tis = tbmapper.selectList(new QueryWrapper<TBtpMtlCurriculumViateTi>()
                                .eq("task_no", taskTon)
                                .eq("item_code", i.getFMaterielCode()));
                        if (IterUtil.isNotEmpty(tis)) {
                            mtlVendorName = tis.get(0).getMtlVendorName();
                        }

                        //如果已经绑定成功过就不需要再进行绑定
                        List<EmsBarcodeRelation> emsBarcodeRelations = emsBarcodeRelationMapper.selectList(new QueryWrapper<EmsBarcodeRelation>()
                                .eq("bar_code", keymatBind.getFNumber())
                                .eq("son_bar_code", i.getFMaterielBarcode())
                                .isNull("segment5")
                                .like("res", "Success")
                        );
                        if(IterUtil.isEmpty(emsBarcodeRelations)){
                            // todo 进行华为父子条码追溯信息接口发送
                            String res = this.sendHuaweitmzs(i, keymatBind, h4, mtlVendorName);

                            //本地数据存储
                            EmsBarcodeRelation emsBarcodeRelation = new EmsBarcodeRelation(i, keymatBind);
                            emsBarcodeRelation.setPo(taskTon);
                            emsBarcodeRelation.setSegment3(taskTon);
                            emsBarcodeRelation.setEmsTransId(h4);
                            emsBarcodeRelation.setSupplier(mtlVendorName);
                            emsBarcodeRelation.setRes(res);
                            emsBarcodeRelationMapper.insert(emsBarcodeRelation);
                        }
                        logger.info("=====================sn消费结束====================");
                    }

                });
            }

            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("MES_TO_MOM_KEYMAT_BIND消费成功");
        } catch (Exception e) {

            //消费异常进行日志记录
            interfaceLogUtil.insertLog(new String(data, CharsetUtil.UTF_8),
                    startDate, new Date(), InterfaceLogUtil.DIR_MES_MOM,
                    InterfaceLogUtil.TYPE_RABBITMQ, e.getMessage(),
                    InterfaceLogUtil.INTERFACENAME_EXCEPTION_GJWLBD
            );

            //如果异常为网络异常的类型，将数据保存，用定时任务方式后续定期重传
            if(e.getMessage().equals(InterfaceLogUtil.TYPE_EXCEPTION_WL)){
                this.saveExceptionWl(new String(data, CharsetUtil.UTF_8),InterfaceLogUtil.INTERFACENAME_EXCEPTION_GJWLBD,startDate);
            }

            //丢弃这条消息  如果设置为 true，消息会被重新放回队列；如果设置为 false，消息将被丢弃或发送到死信队列（如果已配置）。
            channel.basicReject( message.getMessageProperties().getDeliveryTag(),false);
            logger.error("MES_TO_MOM_KEYMAT_BIND消费失败");
        }

    }

    /**
     * mq网络消费异常数据存储
     * @param dataStr
     * @param type
     * @param startDate
     */
    public void saveExceptionWl(String dataStr, String type,Date startDate) {
        MqExceptionData mqExceptionData = new MqExceptionData();
        mqExceptionData.setContentStr(dataStr);
        mqExceptionData.setMqType(type);
        mqExceptionData.setCreateTime(startDate);
        mqExceptionDataMapper.insert(mqExceptionData);

    }


    /**
     * 请求华为父子条码追溯接口 webservice
     *
     * @param dto
     * @param keymatBind
     */
    public String sendHuaweitmzs(MaterialDatasDTO dto, KeymatBind keymatBind, String H4, String mtlVendorName) {
        ProdOrder prodOrder = prodOrderMapper.selectOne(new QueryWrapper<ProdOrder>().eq("order_code", keymatBind.getFPlanNo()));

        //改为https方式传输数据20250415
//        String date = DateUtil.format(new Date(), "yyyyMMdd'T'HHmmss'Z'");
//        BarcodeRelationSendDTO barcodeRelationSendDTO = new BarcodeRelationSendDTO(dto, keymatBind, H4,mtlVendorName,prodOrder);
//        String res = HuaweiInterfaceHttps.sendHuawei(HuaweiInterfaceHttps.serviceUriBarcodeRelationSend,HuaweiInterfaceHttps.http_medhod_BarcodeRelationSend,
//                JSONUtil.toJsonStr(barcodeRelationSendDTO),date);

        String xml = "<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<BarcodeRelationSend>\n" +
                "<Import>\n" +
                "<PO>" + prodOrder.getTaskTon() + "</PO>\n" +
                "<VendorID>22827731</VendorID>\n" +
                "<ORGID>157</ORGID>\n" +
                "<ItemCode>" + keymatBind.getFProdCodeNo() + "</ItemCode>\n" +
                "<Barcode>" + keymatBind.getFNumber() + "</Barcode>\n" +
                "<SonBarcode>" + dto.getFMaterielBarcode() + "</SonBarcode>\n" +
                "<SonItemCode>" + dto.getFMaterielCode() + "</SonItemCode>\n" +
                "<Quantity>1</Quantity>\n" +
                "<Supplier>" + mtlVendorName + "</Supplier>\n" +
                "<Manufactory></Manufactory>\n" +
                "<UploadFlag>0</UploadFlag>\n" +
                "<CheckMessage></CheckMessage>\n" +
                "<CreatedBy>LD001</CreatedBy>\n" +
                "<CreatedDate>" + DateUtil.format(dto.getFDate(), "yyyy-MM-dd HH:mm:ss") + "</CreatedDate>\n" +
                "<UpdatedBy></UpdatedBy>\n" +
                "<UpdatedDate></UpdatedDate>\n" +
                "<Segment1>N</Segment1>\n" +
                "<Segment2>N</Segment2>\n" +
                "<Segment3>" + prodOrder.getTaskTon() + "</Segment3>\n" +
                "<Segment4></Segment4>\n" +
                "<Segment5></Segment5>\n" +
                "<Segment6></Segment6>\n" +
                "<Segment7></Segment7>\n" +
                "<ItemID></ItemID>\n" +
                "<SonItemID></SonItemID>\n" +
                "<CheckFlag>0</CheckFlag>\n" +
                "<EmsTransID>" + H4 + "</EmsTransID>\n" +
                "<CheckInfo></CheckInfo>\n" +
                "<Segment8></Segment8>\n" +
                "<Segment9></Segment9>\n" +
                "<Segment10>" + dto.getFMaterielCode() + "</Segment10>\n" +
                "<Segment11>" + keymatBind.getFProdCodeNo() + "</Segment11>\n" +
                "<Segment12></Segment12>\n" +
                "<Segment13></Segment13>\n" +
                "<Segment14>40033</Segment14>\n" +
                "<Segment15>EMS</Segment15>\n" +
                "</Import>\n" +
                "</BarcodeRelationSend>]]>";


        SoapClient client = SoapClient.create("http://cmes.huawei.com/hw_manufacture/MidLayer.asmx")
                .setMethod("Get_Info_Frmbarcode", "http://Auto.huawei.com.cn/")
                .setParam("sTaskType", "BarcodeRelationSend")
                .setParam("sImport", xml);

        // 发送请求，参数true表示返回一个格式化后的XML内容
        // 返回内容为XML字符串，可以配合XmlUtil解析这个响应
        String send = client.send(true);
        JSONObject object = XML.toJSONObject(send);
        Map map3 = JSONUtil.toBean(JSONUtil.toJsonStr(object), Map.class);
        String res = JSONUtil.toJsonStr(map3);
        return res;

    }


    @RabbitListener(queues = "MES_TO_MOM_DATA_COLLECTION")
    public void queueCollection(byte[] data, Channel channel, Message message) throws IOException {
        //消费开始时间
        Date startDate = new Date();

        try {
            Map maps = (Map) JSON.parse(new String(data, CharsetUtil.UTF_8));
            Object body = maps.get("Body");
            String jsonDatas = JSONUtil.toJsonStr(body);
            logger.info("MES_TO_MOM_DATA_COLLECTION收到:{},收到时间:{}", jsonDatas, DateUtil.now());
            //你的业务逻辑
            if (StrUtil.isNotEmpty(jsonDatas)) {
                DataCollection dataCollection = JSONUtil.toBean(jsonDatas, DataCollection.class);
                dataCollection.setCreateBy("admin");
                dataCollection.setCreateTime(new Date());
                dataCollectionMapper.insert(dataCollection);
                List<DataCollectionInfo> dataList = dataCollection.getDataList();

                if (MesEnum.OP010_1.getCode().equals(dataCollection.getFProcessID())) {
                    for (int i = 0; i < dataList.size(); i++) {
                        dataList.get(i).setCollectionId(dataCollection.getCollectionId());
                        dataList.get(i).setCreateBy("admin");
                        dataList.get(i).setCreateTime(new Date());
                        dataCollectionInfoMapper.insert(dataList.get(i));
                    }
                    String h4 = iBaseSerialNumberService.getSerialNumber("H4", 10);
                    //todo 测试先注释后续放开 进行华为条码属性回传
                    String res = this.sendAttribute(dataCollection, h4);

                    //本地数据存储
                    ProdOrder prodOrder = prodOrderMapper.selectOne(new QueryWrapper<ProdOrder>().eq("order_code", dataCollection.getFPlanNo()));
                    EmsBarcodeAttribute emsBarcodeAttribute = new EmsBarcodeAttribute(dataCollection);
                    emsBarcodeAttribute.setEmsTransId(h4);
                    emsBarcodeAttribute.setPo(prodOrder.getTaskTon());
                    emsBarcodeAttribute.setSegment5(prodOrder.getTaskTon());
                    emsBarcodeAttribute.setCreatedBy(dataCollection.getFAccount() + "/" + dataCollection.getFUserName());
                    //todo 测试先注释后续放开
                    emsBarcodeAttribute.setRes(res);
                    emsBarcodeAttributeMapper.insert(emsBarcodeAttribute);
                } else if (MesEnum.OP040.getCode().equals(dataCollection.getFProcessID())) {

                    //进行客户条码回传
                    this.sendCustomerSNAndHWSNRela(dataCollection,new String(data, CharsetUtil.UTF_8));

                }
            }
            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("MES_TO_MOM_DATA_COLLECTION消费成功");
        } catch (Exception e) {

            //消费异常进行日志记录
            interfaceLogUtil.insertLog(new String(data, CharsetUtil.UTF_8),
                    startDate, new Date(), InterfaceLogUtil.DIR_MES_MOM,
                    InterfaceLogUtil.TYPE_RABBITMQ, e.getMessage(),
                    InterfaceLogUtil.INTERFACENAME_EXCEPTION_GZXF
            );

            //如果异常为网络异常的类型，将数据保存，用定时任务方式后续定期重传
            if(e.getMessage().equals(InterfaceLogUtil.TYPE_EXCEPTION_WL)){
                this.saveExceptionWl(new String(data, CharsetUtil.UTF_8),InterfaceLogUtil.INTERFACENAME_EXCEPTION_GZXF,startDate);
            }

            //丢弃这条消息  如果设置为 true，消息会被重新放回队列；如果设置为 false，消息将被丢弃或发送到死信队列（如果已配置）。
            channel.basicReject( message.getMessageProperties().getDeliveryTag(),false);
            logger.error("MES_TO_MOM_DATA_COLLECTION消费失败" + data);
        }

    }

    /**
     * 客户条码回传
     *
     * @param ction
     */
    public void sendCustomerSNAndHWSNRela(DataCollection ction,String data) {
        //接口开始时间
        Date startDate = new Date();

        ProdOrder prodOrder = prodOrderMapper.selectOne(new QueryWrapper<ProdOrder>().eq("order_code", ction.getFPlanNo()));

        //回传参数封装
        CustomerSNAndHWSNRelaDTO dto = new CustomerSNAndHWSNRelaDTO();
        dto.setPartNo(ction.getFProdCodeNo());
        dto.setLinkedCustomKeyname("CUSTOMER_SN");
        dto.setCustomLinkId(iBaseSerialNumberService.getSerialNumber("H4", 5));
        dto.setTaskNo(prodOrder.getTaskTon());
        dto.setCreationDate(ction.getFDate());
        dto.setCreatedBy(ction.getFAccount());
        dto.setCreatedByName(ction.getFUserName());
        dto.setSn(ction.getFNumber());
        dto.setLinkedCustomValue(ction.getAssemblyCode());
        dto.setSiteId("40033");
        dto.setSnType("10");
        String fProdCodeNo = ction.getFProdCodeNo();
        // 查找字符 '-' 的位置
        int index = fProdCodeNo.indexOf("-");
        // 如果找到 '-'，则取它前面的字符
        if (index != -1) {
            fProdCodeNo = fProdCodeNo.substring(0, index);
        }
        if ("02600628".equals(fProdCodeNo) || "02600551".equals(fProdCodeNo) || "02600552".equals(fProdCodeNo)) {
            dto.setLinkType("460");
        } else if ("02600599".equals(fProdCodeNo) || "02600549".equals(fProdCodeNo) || "02600535".equals(fProdCodeNo)) {
            dto.setLinkType("465");
        } else if ("02600626".equals(fProdCodeNo) || "02600547".equals(fProdCodeNo)) {
            dto.setLinkType("40");
        } else if ("02600627".equals(fProdCodeNo) || "02600507".equals(fProdCodeNo)) {
            dto.setLinkType("200");
        } else if ("02600331".equals(fProdCodeNo) || "02600149".equals(fProdCodeNo)) {
            dto.setLinkType("470");
        } else if ("02601171".equals(fProdCodeNo) || "02600548".equals(fProdCodeNo)) {
            dto.setLinkType("180");
        } else {
            dto.setLinkType("");
        }


        String body = HttpRequest.post(IpAddressConstant.HUAWEI_IP)
                .header("X-HW-ID", "com.huawei.manufacture.mdip.ah.cqld")
                .header("X-HW-APPKEY", "cH0Tg+3El7Ss/11iJnH95g==")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(dto))
                .execute().body();
        Map map = JSONUtil.toBean(body, Map.class);
        String status = String.valueOf(map.get("status"));
        if (!"200".equals(status)) {
            //客户条码回传失败日志记录
            interfaceLogUtil.insertLog(JSONUtil.toJsonStr(dto),
                    startDate, new Date(), InterfaceLogUtil.DIR_MES_MOM,
                    InterfaceLogUtil.TYPE_HTTP, body,
                    InterfaceLogUtil.INTERFACENAME_EXCEPTION_KHTMHC
            );
        }else if("400".equals(status)){
            //如果回调状态为400需要进行重传逻辑
            this.saveExceptionWl(data,InterfaceLogUtil.INTERFACENAME_EXCEPTION_GZXF,startDate);
        }
        //本地数据存储
        EmsCustomerSn emsCustomerSn = new EmsCustomerSn();
        BeanUtils.copyProperties(dto, emsCustomerSn);
        // todo 测试先注释后续放开
        emsCustomerSn.setRes(body);
        emsCustomerSnMapper.insert(emsCustomerSn);

    }

    @RabbitListener(queues = "MES_TO_MOM_MESSAGE_PUSHING")
    public void queuePushing(byte[] data, Channel channel, Message message) throws IOException {
        Date startDate = new Date();
        try {
            Map maps = (Map) JSON.parse(new String(data, CharsetUtil.UTF_8));
            Object body = maps.get("Body");
            String jsonDatas = JSONUtil.toJsonStr(body);
            logger.info("MES_TO_MOM_MESSAGE_PUSHING收到:{},收到时间:{}", jsonDatas, DateUtil.now());
            //你的业务逻辑
            MesAralmDTO mesAralmDTO = JSONUtil.toBean(jsonDatas, MesAralmDTO.class);
            MesAralm mesAralm = new MesAralm();
            BeanUtils.copyProperties(mesAralmDTO, mesAralm);
            mesAralmMapper.insert(mesAralm);

            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("MES_TO_MOM_MESSAGE_PUSHING消费成功");
        } catch (Exception e) {

            //消费异常进行日志记录
            interfaceLogUtil.insertLog(new String(data, CharsetUtil.UTF_8),
                    startDate, new Date(), InterfaceLogUtil.DIR_MES_MOM,
                    InterfaceLogUtil.TYPE_RABBITMQ, e.getMessage(),
                    InterfaceLogUtil.INTERFACENAME_EXCEPTION_GJ
            );

            //丢弃这条消息  如果设置为 true，消息会被重新放回队列；如果设置为 false，消息将被丢弃或发送到死信队列（如果已配置）。
            channel.basicReject( message.getMessageProperties().getDeliveryTag(),false);
            logger.error("MES_TO_MOM_MESSAGE_PUSHING消费失败" + data);
        }

    }

    /**
     * 华为条码属性回传
     *
     * @param ction
     */
    public String sendAttribute(DataCollection ction, String H4) {
        ProdOrder prodOrder = prodOrderMapper.selectOne(new QueryWrapper<ProdOrder>().eq("order_code", ction.getFPlanNo()));

        //改为https传输方式20250415
//        String date = DateUtil.format(new Date(), "yyyyMMdd'T'HHmmss'Z'");
//        SubmitBarcodeReleationDTO submitBarcodeReleationDTO = new SubmitBarcodeReleationDTO(H4,prodOrder,ction);
//        HuaweiInterfaceHttps.sendHuawei(HuaweiInterfaceHttps.serviceUriSubmitBarcodeReleation,HuaweiInterfaceHttps.http_medhod_SubmitBarcodeReleation,
//                JSONUtil.toJsonStr(submitBarcodeReleationDTO),date);

        String xml = "<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<SubmitBarcodeReleation>\n" +
                "<Import>\n" +
                "<EmsTransID>" + H4 + "</EmsTransID>\n" +
                "<OrganizationID>157</OrganizationID>\n" +
                "<PO>" + prodOrder.getTaskTon() + "</PO>\n" +
                "<ItemNumber>" + ction.getFProdCodeNo() + "</ItemNumber>\n" +
                "<ItemVer></ItemVer>\n" +
                "<EmsCode>H4</EmsCode>\n" +
                "<VendorId>22827731</VendorId>\n" +
                "<Sn>" + ction.getFNumber() + "</Sn>\n" +
                "<Barcode2d></Barcode2d>\n" +
                "<Coo>CN</Coo>\n" +
                "<Updated_by></Updated_by>\n" +
                "<Updated_date>" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "</Updated_date>\n" +
                "<Created_by>" + ction.getFAccount() + "/" + ction.getFUserName() + "</Created_by>\n" +
                "<Created_date>" + ction.getFDate() + "</Created_date>\n" +
                "<Attribute1></Attribute1>\n" +
                "<Attribute2></Attribute2>\n" +
                "<Attribute3></Attribute3>\n" +
                "<Attribute4></Attribute4>\n" +
                "<Attribute5>" + prodOrder.getTaskTon() + "</Attribute5>\n" +
                "<Segment1>40033</Segment1>\n" +
                "<Segment2>1D</Segment2>\n" +
                "<Segment3></Segment3>\n" +
                "<Segment4></Segment4>\n" +
                "<Segment5></Segment5>\n" +
                "<Type></Type>\n" +
                "<RoshFlag>Y</RoshFlag>\n" +
                "</Import>\n" +
                "</SubmitBarcodeReleation>]]>";

        SoapClient client = SoapClient.create("http://cmes.huawei.com/hw_manufacture/MidLayer.asmx")
                .setMethod("Get_Info_Frmbarcode", "http://Auto.huawei.com.cn/")
                .setParam("sTaskType", "SubmitBarcodeReleation")
                .setParam("sImport", xml);

        // 发送请求，参数true表示返回一个格式化后的XML内容
        // 返回内容为XML字符串，可以配合XmlUtil解析这个响应
        String send = client.send(true);
        JSONObject object = XML.toJSONObject(send);
        Map map3 = JSONUtil.toBean(JSONUtil.toJsonStr(object), Map.class);
        String res = JSONUtil.toJsonStr(map3);

        return res;

    }

    @RabbitListener(queues = "MES_TO_MOM_DATA_CASENUMBER")
    public void queueCasenumber(byte[] data, Channel channel, Message message) throws IOException {
        //消费开始时间
        Date startDate = new Date();
        //wms回传结果
        String res = "";
        try {
            Map maps = (Map) JSON.parse(new String(data, CharsetUtil.UTF_8));
            Object body = maps.get("Body");
            String jsonDatas = JSONUtil.toJsonStr(body);
            logger.info("MES_TO_MOM_DATA_CASENUMBER收到:{},收到时间:{}", jsonDatas, DateUtil.now());
            //你的业务逻辑
            JSONArray array = JSONUtil.parseArray(jsonDatas);
            List<RptInPackageDTO> dtoList = JSONUtil.toList(array, RptInPackageDTO.class);
            //华为出库回传
            if (IterUtil.isNotEmpty(dtoList)) {
                dtoList.stream().forEach(i -> {
                    List<EmsBarcodeShipment> huaweiTask = i.getHuaweiTask();
                    if (IterUtil.isNotEmpty(huaweiTask)) {
                        huaweiTask.stream().forEach(j -> {
                            j.setLastupdateBy(j.getCreatedBy());
                            j.setLastupdateDate(j.getCreatedDate());
                            shipmentMapper.insert(j);
                        });
                    }
                });
            }
            res = wmsService.sedPackage(dtoList);
            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("MES_TO_MOM_DATA_CASENUMBER消费成功");
        } catch (Exception e) {

            //消费异常进行日志记录
            interfaceLogUtil.insertLog(new String(data, CharsetUtil.UTF_8),
                    startDate, new Date(), InterfaceLogUtil.DIR_MES_MOM,
                    InterfaceLogUtil.TYPE_RABBITMQ,
                    e.getMessage()+"【wms包装接口返回结果:" + res+"】",
                    InterfaceLogUtil.INTERFACENAME_EXCEPTION_BZ
            );
            //丢弃这条消息  如果设置为 true，消息会被重新放回队列；如果设置为 false，消息将被丢弃或发送到死信队列（如果已配置）。
            channel.basicReject( message.getMessageProperties().getDeliveryTag(),false);
            logger.error("MES_TO_MOM_DATA_CASENUMBER消费失败");
        }

    }



}
